<template>
  <div>
    <van-nav-bar
      title="导入成员"
      v-if="windows === 1"
      fixed
      @click-left="back()"
      right-text="添加"
      @click-right="add()"
    >
      <template #left>
        <van-icon name="arrow-left" size="18" />
      </template>
    </van-nav-bar>
    <form action="/">
      <van-search
        v-model="value"
        placeholder="搜索"
        input-align="center"
        shape="round"
        :style="{marginTop:windows===1 ? '48px':'0px'}"
        @search="onSearch1()"
      />
    </form>
    <form action="/">
      <van-dropdown-menu v-if="windows === 1">
        <van-dropdown-item v-model="value1" :options="option1" />
        <van-dropdown-item v-model="value2" :options="option2" />
        <van-dropdown-item v-model="value3" :options="option3" />
        <div class="flex-container">
          <van-button type="info" @click.prevent="onSearch2()" class="flex-item"
            >查询</van-button
          >
          <van-button
            type="primary"
            @click.prevent="checkAll()"
            class="flex-item"
            >全选</van-button
          >
          <van-button
            type="info"
            @click.prevent="ReverseAll()"
            class="flex-item"
            >反选</van-button
          >
        </div>
      </van-dropdown-menu>

      <div class="flex-container" v-if="windows === 0">
        <div class="dropdown-menu">
          <el-dropdown trigger="click" v-if="windows === 0" class="flex-item">
            <span class="el-dropdown-link">
              {{ value01 }}
            </span>
            <el-dropdown-menu slot="dropdown" class="custom-dropdown-menu">
              <el-dropdown-item
                v-for="(item, index) in option1"
                :key="index"
                @click.native="(value1 = item.value), (value01 = item.text)"
                >{{ item.text }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <el-dropdown trigger="click" v-if="windows === 0" class="flex-item" p>
          <div class="dropdown-menu">
            <span class="el-dropdown-link">
              {{ value02 }}
            </span>
            <el-dropdown-menu slot="dropdown" class="custom-dropdown-menu">
              <el-dropdown-item
                v-for="(item, index) in option2"
                :key="index"
                @click.native="(value2 = item.value), (value02 = item.text)"
                >{{ item.text }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </div>
        </el-dropdown>

        <el-dropdown trigger="click" v-if="windows === 0" class="flex-item">
          <div class="dropdown-menu">
            <span class="el-dropdown-link">
              {{ value03 }}
            </span>
            <el-dropdown-menu slot="dropdown" class="custom-dropdown-menu">
              <el-dropdown-item
                v-for="(item, index) in option3"
                :key="index"
                @click.native="(value3 = item.value), (value03 = item.text)"
                >{{ item.text }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </div>
        </el-dropdown>
        <el-button type="primary" class="flex-item" @click.prevent="onSearch2()"
          >查询</el-button
        >
        <el-button type="success" class="flex-item" @click.prevent="checkAll()"
          >全选</el-button
        >
        <el-button type="info" class="flex-item" @click.prevent="ReverseAll()"
          >反选</el-button
        >
        <el-button type="primary" class="flex-item" @click.prevent="add()"
          >添加</el-button
        >
      </div>
    </form>

    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <!-- <div v-for="(item, index) in datas" :key="index"> -->
      <van-collapse v-model="activeName" accordion>
        <div v-for="(user, userIndex) in datas.user_list" :key="userIndex">
          <van-cell
            clickable
            :key="userIndex"
            :title="user.chname"
            @click="toggleCheckbox(user.id)"
          >
            <template #right-icon>
              <input
                type="checkbox"
                :id="'user_' + user.id"
                v-model="result"
                :value="user.id"
              />
            </template>
          </van-cell>
        </div>
      </van-collapse>
      <!-- </div> -->
    </van-list>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "SelectImport",
  data() {
    return {
      fin: 0,
      windows: 0,
      result: [],
      search: "搜索",
      value: "",
      value1: 0,
      value2: 0,
      value3: 0,
      value01: "年级",
      value02: "专业",
      value03: "班级",
      option1: [
        { text: "年级", value: 0 },
        { text: "2018级", value: 2018 },
        { text: "2019级", value: 2019 },
        { text: "2020级", value: 2020 },
        { text: "2021级", value: 2021 },
        { text: "2023级", value: 2023 },
        { text: "2024级", value: 2024 },
        { text: "2025级", value: 2025 },
        { text: "2026级", value: 2026 },
        { text: "2027级", value: 2027 },
        { text: "2028级", value: 2028 },
        { text: "2029级", value: 2029 },
        { text: "2030级", value: 2030 },
      ],
      option2: [
        { text: "专业", value: 0 },
      ],
      option3: [
        { text: "班级", value: 0 },
        { text: "1班", value: 401 },
        { text: "2班", value: 402 },
        { text: "3班", value: 403 },
        { text: "4班", value: 404 },
        { text: "5班", value: 405 },
      ],
      activeName: ["1"],
      datas: [],
      fin: 0,
      loading: false,
      finished: false,
      checked: true,
      activeIcon: "https://img01.yzcdn.cn/vant/user-active.png",
      inactiveIcon: "https://img01.yzcdn.cn/vant/user-inactive.png",
    };
  },
  mounted() {
    if (window.innerWidth < 768) {
      this.windows = 1;
    } else {
      this.windows = 0;
    }
    window.addEventListener('keyup', this.handleKeyup);
    axios.post("/class/selectMajors").then((response) => {
      console.log(111);
      console.log(response);
      response.data.data.forEach((item) => {
        this.option2.push({
          text: item.major_name,
          value: item.major_id,
        });
      });
      // this.datas = response.data.data;
    });
    // console.log(this.$route.params.id);
    axios
      .post("/user/list?classId=" + this.$route.params.id)
      .then((response) => {
        // console.log(response.data);
        this.datas = response.data.data;
        // console.log(this.datas);
        // console.log(this.datas.user_id_list);
        // console.log(this.datas.user_list[0].id);
        this.checks();
      });
  },
  beforeDestroy() {
    window.removeEventListener('keyup', this.handleKeyup);
  },
  methods: {
    handleKeyup(event) {
      const inputBuffer = [];

      // 监听用户键入的字符
      document.addEventListener('keypress', (e) => {
        inputBuffer.push(String.fromCharCode(e.which));
        // console.log(e);

        // 只保留最后 7 个字符
        if (inputBuffer.length > 8) {
          inputBuffer.shift();
        }
        // 检查输入是否匹配 'addMajor'
        if (inputBuffer.join('').toLowerCase() === 'addmajor') {
          window.removeEventListener('keyup', this.handleKeyup);
          this.$router.push("/addMajor");
        }
        if (inputBuffer.join('').toLowerCase() === 'delmajor') {
          window.removeEventListener('keyup', this.handleKeyup);
          this.$router.push("/delMajor");
        }
      });
    },
    checks() {
      // 在数据加载完成后，对于每个 user，如果其 user_id 在 user_id_list 中，则将其添加到结果列表中
      this.datas.user_list.forEach((user) => {
        if (this.datas.user_id_list.includes(user.id)) {
          // 如果 user_id 在 user_id_list 中，则将其添加到结果列表中
          if (!this.result.includes(user.id)) {
            this.result.push(user.id);
          }
        }
      });
    },

    checkAll() {
      this.result = this.datas.user_list.map((user) => user.id); // 全选
    },
    ReverseAll() {
      this.result = []; // 反选
    },

    add() {
      console.log(this.result.value);
      axios
        .post(
          "/class/importbylist?classId=" +
            this.$route.params.id +
            "&list=" +
            this.result
        )
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("导入成功");
          } else {
            this.$message.error("导入失败");
          }

          this.$router.go(-1);
        });
    },

    toggleCheckbox(userId) {
      // 根据用户ID切换复选框的选中状态
      const index = this.result.indexOf(userId);
      if (index !== -1) {
        this.result.splice(index, 1); // 取消选中
      } else {
        this.result.push(userId); // 选中
      }
    },
    onSearch1() {
      console.log(this.value);
      axios
        .post("/class/selectusers?message=" + this.value)
        .then((response) => {
          console.log(response);
          this.datas.user_list = response.data.data;
        });
    },
    onSearch2() {
      axios
        .post(
          "/user/Select?nj=" +
            this.value1 +
            "&zy=" +
            this.value2 +
            "&bj=" +
            this.value3
        )
        .then((response) => {
          // console.log(response);
          // console.log(this.datas.user_list);
          this.datas.user_list = response.data.data;
          this.checks();
        });
      console.log(this.value1, this.value2, this.value3);
    },
    onLoad() {
      setTimeout(() => {
        for (let i = 0; i < 1000; i++) {
          this.fin += 1;
        }

        this.loading = false;

        if (this.fin >= this.datas.user_list.length) {
          this.finished = true;
        }
      }, 1000);
    },
    ToCreateCourse() {
      this.$router.push("CreateCourse");
    },
    back() {
      this.$router.go(-1);
    },
  },
};
</script>

<style scoped>
.blue-text {
  color: skyblue;
}

.red-text {
  color: rgb(116, 193, 0);
}

.search-btn {
  margin-left: 10%;
  margin-top: 10%;
  width: 80%;
  position: absolute;
  bottom: 20%;
}

.img-icon {
  height: 20px;
}

.flex-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* flex:1; */
}

.flex-item {
  flex: 1;
}

input[type="checkbox"] {
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;
  -ms-appearance: none;
  display: inline-block;
  width: 20px;
  height: 20px;
  transition: border-color 0.3s;
  cursor: pointer;
}

/* 复选框标记的样式 */
input[type="checkbox"]:checked::before {
  content: "✔"; /* 选中后显示✔符号 */
  display: block;
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  color: white;
  border-radius: 50%; /* 使复选框变成圆形 */
  transition: border-color 0.3s;
  background-color: rgb(70, 175, 240); /* 选中后的背景色 */
  cursor: pointer;
}

input[type="checkbox"]:checked::after {
  display: none; /* 显示 ✔ 符号 */
}

.flex-container {
  display: flex;
  justify-content: space-between;
}

.flex-item {
  flex: 1;
  margin: 0 5px; /* 添加适当的间距 */
}

.el-dropdown-link {
  /* border: #409EFF 1px solid; */
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.dropdown-menu {
  border: #b5c7fe 1px solid;
  border-radius: 10%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  /* color: rgb(0, 0, 0); */
  /* background-color: #adb4bb; */
}

.custom-dropdown-menu {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 启用垂直滚动条 */
}
</style>